<template>
    <div id="NoticeEditor" style="line-height:20px"></div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import WangEditor from 'wangeditor'
import { uploadQiniu } from '@/utils/upload'
@Component({
  name: 'Editor'
})
export default class Editor extends Vue {
    private editor: any = null
    private content: string = ''
    /**
     * 创建编辑器
     */
    private createEdit (content: string): void {
      this.editor = new WangEditor('#NoticeEditor')
      this.editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'image',
        'table',
        'undo',
        'redo'
      ]
      this.editor.config.showFullScreen = true
      this.editor.config.height = 200
      this.editor.config.zIndex = 10
      this.editor.config.uploadImgMaxLength = 1
      this.editor.config.uploadImgMaxSize = 20 * 1024 * 1024
      this.editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
      const initConfig = (this as any).$store.state.common.initConfig
      const doMain = initConfig && initConfig.qiniuDomainMap ? initConfig.qiniuDomainMap.im : ''
      this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
        const request = {
          file: resultFiles[0],
          onError: () => '',
          onProgress: () => '',
          onSuccess: (data: any) => {
            if (data.key) {
              insertImgFn(`${doMain}/${data.key}`)
            } else {
              return false
            }
          }
        }
        uploadQiniu({ type: 'im', fileName: resultFiles[0].name }, request)
      }
      this.editor.config.onchange = (newHtml) => {
        if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(newHtml)) {
          newHtml = newHtml.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#ecf0f3">')
        }
        this.content = newHtml
      }
      this.editor.create()
      this.editor.txt.html(content)
    }

    /**
     * 销毁编辑器
     */
    private destoryEditor () {
      if (this.editor) {
        this.editor.destroy()
        this.editor = null
        this.content = ''
      }
    }
}
</script>
